<template>
  <div ref="warp" class="contentWarpBox">
    <div class="searchInfo">
      <div class="left">
        <el-select
          v-if="resultDics.MEMBER_LEVEL"
          v-model="getSearchInfo.memberLevel"
          style="width:120px;"
          clearable
          placeholder="客户等级"
        >
          <el-option
            v-for="item in resultDics.MEMBER_LEVEL.children"
            :key="item.dicCode"
            :label="item.dicName"
            :value="item.dicCode"
          />
        </el-select>
        <el-select
          v-if="resultDics.SALES_PHASE"
          v-model="getSearchInfo.salesStage"
          style="width:120px;"
          clearable
          placeholder="销售阶段"
        >
          <el-option
            v-for="item in resultDics.SALES_PHASE.children"
            :key="item.dicCode"
            :label="item.dicName"
            :value="item.dicCode"
          />
        </el-select>
        <el-input v-model="getSearchInfo.projectName" placeholder="商机名" style="width:120px" />
        <el-input v-model="getSearchInfo.keyword" placeholder="会员名称" style="width:120px" />
        <el-button type="primary" @click="searchInfoMation">搜 索</el-button>
      </div>
      <el-button
        v-if="accreditChildren.createSale"
        class="right"
        type="primary"
        @click="jump('create')"
      >新增销售线索</el-button>
    </div>
    <el-table
      ref="table"
      :data="tableData"
      :height="this.$getTableHeight"
      :span-method="objectSpanMethod"
      border
      stripe
    >
      <el-table-column width="120" prop="memberName" show-overflow-tooltip label="客户" />
      <el-table-column width="120" label="商机" show-overflow-tooltip>
        <template slot-scope="scope">
          <div v-if="scope.row.id" style="text-align:center;line-height:37px;">
            <span
              v-if="scope.row.projectName"
              class="blockBox blue"
              @click.stop="changeActive(scope.row.id)"
            >{{ scope.row.projectName }}</span>
            <el-button
              v-else
              type="primary"
              icon="el-icon-edit-outline"
              @click.stop="changeActive(scope.row.id)"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column width="120" prop="executor" label="负责人" show-overflow-tooltip />
      <el-table-column prop="Label" show-overflow-tooltip label="标签">
        <template slot-scope="scope">
          <span v-if="scope.row.label">
            <el-tag
              v-for="tag in scope.row.label"
              :key="tag.id"
              :style="{color:'#'+tag.color}"
              :disable-transitions="false"
            >{{ tag.label }}</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column width="120" prop="salesStageName" show-overflow-tooltip label="阶段" />
      <el-table-column width="120" prop="content" show-overflow-tooltip label="最新动态" />
      <el-table-column prop="turnoverTime" show-overflow-tooltip label="更新时间" />
      <el-table-column width="120" prop="remark" show-overflow-tooltip label="备注" />
      <el-table-column width="120" prop="source" show-overflow-tooltip label="来源" />
      <el-table-column prop="creationTime" show-overflow-tooltip label="创建时间" />
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <span v-if="accreditChildren.deleteSSale">
            <span v-if="scope.row.id" class="_delete" @click="deleteInfo(scope.row)">删除</span>
            <span v-else>&nbsp;</span>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination clearfix">
      <Pagination
        class="right"
        :total-count="totalCount"
        :page-size="page.pageSize"
        :current-page="page.pageNo"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />
    </div>
    <div :class="active ? 'closeRightBox trans':'openRightBox trans'" @click.stop>
      <detail
        v-if="active"
        :id="jumpId"
        :accredit-children="accreditChildren"
        :page-height="pageHeight"
        :update-right="updateRight"
        @clearJumpId="clearJumpId"
        @editor="openDialog"
      />
    </div>
    <div v-if="dialogTableVisible" @click.stop>
      <el-dialog
        :title="isCreate ? '新增销售线索' : '编辑销售线索'"
        center
        :visible.sync="dialogTableVisible"
        width="800px"
        :close-on-click-modal="false"
        :before-close="handleClose"
      >
        <create :id="jumpId" @closeDialog="handleClose" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import mmUrl from '~/utils/utilUrl';
import detail from '~/components/sale/detail';
import create from '~/components/sale/create';
import {
  trueOrFalse,
  createDics,
  _deleteMethods,
  reduceArr,
  changeTableHeight
} from '~/utils/util';
import Pagination from '~/components/commom/pagination';
export default {
  components: {
    detail,
    Pagination,
    create
  },
  data() {
    return {
      jumpId: '',
      pageHeight: 0,
      updateRight: false,
      isCreate: false,
      active: false,
      loading: true,
      changeSelectOr: false,
      change: false,
      accreditChildren: {},
      dics: [],
      projectType: [],
      tableData: [], // talbe表格数据
      businessCategory: [],
      category: [],
      totalCount: 0,
      getSearchInfo: {
        projectName: '',
        keyword: '',
        salesStage: null,
        memberLevel: null
      },
      copygetSearchInfo: {
        projectName: '',
        keyword: '',
        salesStage: null,
        memberLevel: null
      },
      page: {
        maxResultCount: 0,
        pageNo: 0,
        pageSize: 20,
        skipCount: 0
      },
      dialogTableVisible: false,
      resultDics: {},
      isEditor: false,
      spanArr: [],
      mergeData: {}, // 合并行的记录
      mergePos: {}, // mergeData中每项的索引
      mergeProp: ['memberId', 'memberName']
    }
  },
  mounted() {
    this.initGetDate()
    const result = JSON.parse(sessionStorage.getItem('menu'))
    this.accreditArr = reduceArr(result, '/' + this.$route.name)
    this.accreditChildren = createDics(
      this.accreditArr.children,
      'permissionCode'
    )
  },
  methods: {
    handleClose() {
      this.dialogTableVisible = false
      this.updateRight = !this.updateRight
      this.searchInfoMation('no')
    },
    clearJumpId() {
      this.active = false
      this.jumpId = null
    },
    changeActive(id) {
      this.active = true
      this.jumpId = id
    },
    openDialog() {
      this.isEditor = true
      this.isCreate = false
      this.dialogTableVisible = true
    },
    jump(id) {
      this.dialogTableVisible = true
      this.jumpId = id
      id === 'create' ? (this.isCreate = true) : (this.isCreate = false)
    },
    searchInfoMation(res) {
      res === 'no' ? '' : (this.page.pageNo = 0)
      const result = {}
      result.page = JSON.parse(JSON.stringify(this.page))
      this.copygetSearchInfo = JSON.parse(JSON.stringify(this.getSearchInfo))
      Object.assign(result, this.copygetSearchInfo)
      this.initGetDate(result)
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      const result = {}
      result.page = JSON.parse(JSON.stringify(this.page))
      Object.assign(result, this.copygetSearchInfo)
      this.initGetDate(result)
    },
    handleCurrentChange(val) {
      this.page.pageNo = val
      const result = {}
      result.page = JSON.parse(JSON.stringify(this.page))
      Object.assign(result, this.copygetSearchInfo)
      this.initGetDate(result)
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.mergeProp.includes(column.property)) {
        const _row = Object.keys(this.mergeData).length
          ? this.mergeData[column.property][rowIndex]
          : 1
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    setSpanArr(tableData, keyName) {
      keyName.forEach((kitem, k) => {
        tableData.forEach((data, i) => {
          if (i === 0) {
            this.mergeData[kitem] = this.mergeData[kitem] || []
            this.mergeData[kitem].push(1)
            this.mergePos[kitem] = 0
          } else {
            // 判断当前元素与上一个元素是否相同
            if (data[kitem] === tableData[i - 1][kitem]) {
              this.mergeData[kitem][this.mergePos[kitem]] += 1
              this.mergeData[kitem].push(0)
            } else {
              this.mergeData[kitem].push(1)
              this.mergePos[kitem] = i
            }
          }
        })
      })
    },
    deleteDic(row) {
      trueOrFalse(this).then(() => {
        this.$post({
          url: mmUrl.dic.deleteDic,
          data: {
            id: row.id
          }
        })
          .then(res => {
            this.initGetDate()
          })
          .catch(err => this.$message.error(err))
      })
    },
    initGetDate(res) {
      let data = {}
      if (res) {
        data = res
      } else {
        data.page = JSON.parse(JSON.stringify(this.page))
        Object.assign(data, this.copygetSearchInfo)
      }
      this.$post({
        url: '/manage/saleslead/pageLoad',
        data: data
      }).then(res => {
        this.loading = false
        this.resultDics = createDics(res.dics, 'dicCode')
        this.settingTableDate(res)
        changeTableHeight(this)
      })
    },
    settingTableDate(res) {
      this.spanArr = []
      this.mergeData = {}
      this.totalCount = res.items.totalCount
      res.items.items.forEach(v => {
        v.dtoList.forEach(vv => {
          this.spanArr.push(Object.assign(JSON.parse(JSON.stringify(v)), vv))
        })
      })
      this.tableData = this.spanArr
      this.tableData.forEach(element => {
        if (element.label) element.label = JSON.parse(element.label)
      })
      this.setSpanArr(this.tableData, ['memberId', 'memberName'])
    },
    deleteInfo(row) {
      const that = this
      _deleteMethods('/manage/saleslead/deletedSalesLeads', row, that).then(
        () => {
          that.searchInfoMation('no')
        }
      )
    }
  }
}
</script>

<style lang="scss">
.blockBox {
  display: block;
  width: 100%;
  min-height: 37px;
  cursor: pointer;
}
</style>

